<template>
  <div class="charts-search-block business-select-box">
    <div class="charts-search-block-content">
      <div class="charts-search-select">
        <span>{{$t('common.base.time')}}：</span>
        <el-select :clearable="false" v-model="formData.dataType" :placeholder="$t('common.base.pleaseSelect')" class="business-dateType-picker" @change="changeDateType">
          <el-option
            v-for="item in dataTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-date-picker
          v-if="dataPickerType === 'monthrange'"
          class="business-date-picker business-select-mr"
          v-model="formData.monthTime"
          type="monthrange"
          :range-separator="$t('common.base.to')"
          :start-placeholder="$t('common.base.startDate')"
          :end-placeholder="$t('common.base.endDate')"
          value-format="timestamp"
          :default-time="['00:00:00', '23:59:59']"
          align="right"
          @change="changeTime"
          :clearable="false">
        </el-date-picker>
        <el-date-picker
          v-if="dataPickerType === 'daterange'"
          class="business-date-picker"
          v-model="formData.dateTime"
          type="daterange"
          :range-separator="$t('common.base.to')"
          :start-placeholder="$t('common.base.startDate')"
          :end-placeholder="$t('common.base.endDate')"
          value-format="timestamp"
          :default-time="['00:00:00', '23:59:59']"
          :clearable="false"
          @change="changeTime"
          align="right">
        </el-date-picker>
      </div>
      <div class="charts-search-select">
        <span>OEM：</span>
        <el-select 
          :placeholder="$t('common.base.pleaseSelect')"
          v-model="formData.OEM" 
          @change="changeOem"
          :clearable="true"
          style="width:180px">
          <el-option v-for="item in oemList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('common.base.systemKeyword.customer')}}：</span>
        <biz-search-customer-select style="width:180px" :multiple="true" :value="customerIdList" @input="chooseCustomer" :remote-method="fetchCustomer" value-key="id" :collapsed="true" :placeholder="$t('report.common.allCustomer')"
        />
      </div>
      <div class="charts-search-select usual-biz-team-select">
        <span>{{$t('common.base.department')}}：</span>
        <!-- <el-select v-model="formData.departmentIds" multiple :placeholder="$t('common.base.pleaseSelect')" @change="chooseTags" collapse-tags filterable style="width:180px;">
          <el-option
            v-for="item in tagList"
            :key="item.id"
            :label="item.tagName"
            :value="item.id">
          </el-option>
        </el-select> -->
        <biz-team-select
          :value="formData.departmentIds"
          collapse
          multiple
          style="width:180px;"
          @input="chooseTags"
          :fetch-func="getTagList"
        />
      </div>
      <div class="charts-search-select">
        <span>{{$t('common.base.person')}}：</span>
        <el-select v-model="formData.personUserIds" multiple :placeholder="$t('common.base.pleaseSelect')" collapse-tags filterable style="width:180px;">
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.displayName"
            :value="item.userId">
          </el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('common.fields.planNumber.displayName')}}：</span>
        <el-select v-model="formData.planNumbers" multiple :placeholder="$t('common.base.pleaseSelect')" @change="choosePlans" collapse-tags filterable style="width:180px;">
          <el-option
            v-for="item in planList"
            :key="item.planNumber"
            :label="item.planNumber"
            :value="item.planNumber">
          </el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('task.edit.planName')}}：</span>
        <!-- <el-select v-model="formData.planNames" multiple :placeholder="$t('common.base.pleaseSelect')" @change="choosePlans" collapse-tags filterable style="width:180px;">
          <el-option
            v-for="item in planNameList"
            :key="item.planNumber"
            :label="item.planNumber"
            :value="item.planNumber">
          </el-option>
        </el-select> -->
        <el-input class="flex-1" v-model="formData.planName" :placeholder="$t('common.base.pleaseSelect')" ></el-input>
      </div>
      <div class="charts-search-select">
        <span>{{$t('common.form.preview.taskNo.label')}}：</span>
        <el-select v-model="formData.taskNumbers" multiple :placeholder="$t('common.base.pleaseSelect')" collapse-tags filterable style="width:180px;">
          <el-option
            v-for="item in taskNoList"
            :key="item.taskNo"
            :label="item.taskNo"
            :value="item.taskNo">
          </el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('common.form.preview.serviceItem.label3')}}：</span>
        <el-select 
          :placeholder="$t('common.base.all')" 
          v-model="formData.workTypes"
          multiple
          collapse-tags
          filterable
          :clearable="true"
          style="width:180px">
          <el-option v-for="item in workTypeList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('frameHeader.tabMap.costClassification')}}：</span>
        <el-select 
          :placeholder="$t('common.base.all')" 
          v-model="formData.expensesTypes" 
          :clearable="true"
          multiple
          filterable
          collapse-tags
          style="width:180px">
          <el-option v-for="(item,index) in expensesList" :key="index" :label="item" :value="item"></el-option>
        </el-select>
      </div>
    </div>
    <div class="charts-search-block-operator">
      <el-button type='primary' @click="handlerSearchClick">
        {{ $t('common.base.search') }}
      </el-button>
    </div>
  </div>
</template>
<script>

import { nearDateBy, dayTimeEnd, firstDayOfMonth, lastDayOfMonth } from 'pub-bbx-utils';
import { t } from '@src/locales';
import http from 'src/util/HttpUtil';  
import { 
  getAllSelectDataList,
  getPlanNoList,
  getTaskNoList,
  
} from 'src/api/ssbReports';
import { getTagList } from '@src/api/SettingApi.ts';       
import { getCustomerList } from '@src/api/CustomerApi'

export default {
  name: 'cost-stat-select',
  data() {
    return {
      formData:{
        dateTime: [], // 日时间
        monthTime: [], // 月时间
        departmentIds: [], // 部门
        personUserIds:[], // 人员
        dataType: 'month', // 日月维度
        planNumbers:[],
        taskNumbers:[],
        OEM: '',
        OEMFieldName: '',
        planName: '',
        workTypes: [],
        expensesTypes: []
      },
      customerIdList: [],
      dataTypeList: [
        {
          label:t('common.base.month'),
          value:'month'
        },
        {
          label:t('common.base.day2'),
          value:'day'
        },
      ],
      oemList: [],
      tagList: [], // 部门列表
      userList: [], // 人员列表
      planList:[], // 计划编号列表
      planNameList: [],
      workTypeList: [],
      expensesList: [],
      taskNoList:[], // 工单编号列表
    }
  },
  computed:{
    dataPickerType(){
      return this.formData.dataType === 'month' ? 'monthrange' : 'daterange'
    }
  },
  created() {
    this.formData.dateTime = [+firstDayOfMonth(nearDateBy(5, 'month')), +dayTimeEnd()]
    this.formData.monthTime = [+firstDayOfMonth(nearDateBy(5, 'month')), +dayTimeEnd()]
    this.getRequestParam()
  },
  methods: {
    chooseCustomer(value){
      this.customerIdList = value
    },
    fetchCustomer(params){
      if (this.formData.OEM) {
        params['conditions'] = [{property:this.formData.OEMFieldName, value:this.formData.OEM, key:null, operator:'eq'}]
      } else {
        params['conditions'] = []
      }
      return getCustomerList({...params})
    },
    getOemList(){
      http.get('/api/ssbreport/outside/staff/calendar/getCustomerOEMDatabase').then(res=>{
        if(res.code == 0){
          this.oemList = res.data.database
          this.formData.OEMFieldName = res.data.fieldName
        }
      })
    },
    changeDateType(){
    },
    changeTime(){
    },
    changeOem(){
      this.customerIdList = []
    },
    // 选择计划编号
    choosePlans(){
      this.formData.taskNumbers = []
      this.getTaskNoList()
    },
    getPlanList(){
      let data = {
        'createDateStart':this.formData.dataType == 'month' ? this.formData.monthTime[0] : this.formData.dateTime[0],
        'createDateEnd':this.formData.dataType == 'month' ? +lastDayOfMonth(this.formData.monthTime[1]) : this.formData.dateTime[1],
        'timeDimension':this.formData.dataType
      }
      getPlanNoList(data).then(res=>{
        if(res.code == 0){
          this.planList = res.data
          this.formData.planNumbers = res.data[0] ? [res.data[0].planNumber] : []
          this.getTaskNoList()
          this.getData()
        }
      })
    },
    getTaskNoList(){
      getTaskNoList({planNumbers:this.formData.planNumbers}).then(res=>{
        if(res.code == 0){
          this.taskNoList = res.data
        }
      })
    },
    async getTagList(params){
      try {
        return await getTagList(params);
      } catch (error) {
        console.error("get tag list error", error);
      }
    },
    chooseTags(value){
      this.formData.departmentIds = value;
      this.formData.personUserIds = []
      this.userList = []
      if(this.formData.departmentIds.length == 0) return;
      this.getUserList()
    },
    getUserList(){
      const { departmentIds } = this.formData
      let tagIds_ = [];
      departmentIds.forEach(item=>{
        tagIds_.push(item.id)
      })
      let params = {
        departmentIds:tagIds_,
      }
      http.post('/api/ssbreport/outside/coststatistics/costStatisticsQueryUser', params).then(res=>{
        if(res.code == 0){
          this.userList = res.data
        }
      })
    },
    handlerSearchClick(){
      this.getData()
    },

    /**
     * @des 初始化搜索所需数据
     */
    getRequestParam () {
      // 影响报表内容的需要放在arr
      this.getOemList()
      this.getPlanList()
      getAllSelectDataList().then(res => {
        if (res.code == 0) {
          const { serviceTypes, expenseClassifications } = res.data;
          this.workTypeList = serviceTypes;
          this.expensesList = expenseClassifications;
        }
      })
    },
    getSearchParams(){
      const {departmentIds, personUserIds, planNumbers, taskNumbers, dataType, OEM, monthTime, dateTime, planName, expensesTypes, workTypes } = this.formData;
      const { customerIdList } = this;
      let customerIds = [];
      let tagIds_ = [];
      try {
        customerIdList.forEach(item=>customerIds.push(item.id))
        departmentIds.forEach(item=>{
          tagIds_.push(item.id)
        })
      } catch (error) {
        console.warn(error, 'error try catch customerIdList.forEach');
      }
      let params = {
        createDateStart:dataType == 'month' ? monthTime[0] : dateTime[0],
        createDateEnd:dataType == 'month' ? +lastDayOfMonth(monthTime[1]) : dateTime[1],
        departmentIds:tagIds_,
        personUserIds,
        planNumbers,
        taskNumbers,
        isExport:false,
        timeDimension:dataType,
        oem:OEM ? OEM : '',
        customerIds,
        planName,
        expenseClassifications:expensesTypes,
        serviceTypes:workTypes
      }
      params = {
        ...params,
        createDateStart: new Date(params.createDateStart).getTime(),
        createDateEnd: new Date(params.createDateEnd).getTime(),
      }
      return params
    },
    getData(){
      const params = this.getSearchParams();
      this.$emit('change-loading', {type:1, state:true})

      http.post('/api/ssbreport/outside/coststatistics/costStatisticsReportData', params).then(res=>{
        if(res.code == 0){
          this.$emit('updateData', {data:res.data, haveUsers:this.formData.personUserIds.length > 0})
        }else{
          this.$message.error(res.message)
        }
      }).finally(()=>{
        
        this.$emit('change-loading', {type:1, state:false})
      })
    },
    export(){
      this.$emit('change-loading', {type:2, state:true})
      const params = this.getSearchParams();
      params.isExport = true;
      http.post('/api/ssbreport/outside/coststatistics/exportCostStatisticsReport', params, true, {responseType: 'blob'}).then(blob=>{
        let link = document.createElement('a');
        let url = URL.createObjectURL(blob);
        link.download = this.$t('report.costStatSelect.costStatistics');
        link.href = url;
        document.body.appendChild(link);
        link.click();
        setTimeout(() => {
          URL.revokeObjectURL(url);
          document.body.removeChild(link);
        }, 150);

      }).finally(() =>{
        this.$emit('change-loading', {type:2, state:false})
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../business.scss';
</style>
<style lang="scss">
@import './usualSelcet.scss'
</style>